//
//  HomeVC.m
//  UHealth
//
//  Created by gjtxz on 14/12/29.
//  Copyright (c) 2014年 gjtx. All rights reserved.
//

#import "HomeVC.h"
#import <AudioToolbox/AudioToolbox.h>
#import "HomeMainV.h"

#import "sanbg.h"
#import "NSString+BloodSugar.h"

#import "DBManage.h"
#import "AFNetworking.h"

#import "BLEVC.h"
#import "UserVC.h"

#import "ChartV.h"

#define kLastBindDevice                     @"LastBindDevice"      //最后绑定的蓝牙名字

#define kLastHandleIndex                    @"LastHandleIndex"
#define kLastHandleValue                    @"LastHandleValue"

#define kLastUserID                         @"LastUserID"
#define kLastDeviceID                       @"LastDeviceID"
#define kLastSensorID                       @"LastSensorID"
#define kLastStartMeasureDate               @"LastStartMeasureDate"
#define kLastSensorInitDate                 @"LastSensorInitDate"

#define kReferenceArray                     @"ReferenceArray"       //参比值数据 --init
//参比值
#define kReferenceKey                       @"ReferenceKey"
#define kReferenceIndex                     @"ReferenceIndex"

//最后处理
#define kQueryDBMust    [NSString stringWithFormat:@"%@ = '%d' and %@ = '%@' and %@ = '%@' ",kUserID,_defBSM.userID,kDeviceID,_defBSM.deviceID,kSensorID,_defBSM.sensorID]


@interface HomeVC ()<CBCentralManagerDelegate,CBPeripheralDelegate,UIAlertViewDelegate,CDRTranslucentSideBarDelegate,RatViewDelegate>

//视图
@property (nonatomic,strong) HomeMainV              *mainV;
@property (nonatomic,strong) UIAlertView            *inputReferenceAlert;//输入参比的警告框
@property (nonatomic,strong) UIAlertView            *bindAlert;


@property (nonatomic, strong) UserVC                *leftU;
@property (nonatomic, strong) BLEVC                 *rightB;

//数据
@property (nonatomic,strong) CBPeripheral           *peri;//蓝牙
@property (nonatomic,strong) CBCharacteristic       *cha;//特性


//时间同步
@property (nonatomic)        BOOL                   didSyncTime;//时间同步完成
@property (nonatomic)        NSInteger              syncTimeCount;//时间同步次数10
//绑定设备
@property (nonatomic,strong) NSString               *devicePassword;//设备密码
@property (nonatomic)        BOOL                   didBindDevice;//绑定设备
@property (nonatomic)        NSInteger              bindDeviceCount;//重新请求数据的次数，超过5次，提示硬件出问题了
//设备ID
@property (nonatomic)        BOOL                    didRequestDeviceId;   //请求设备ID
@property (nonatomic)        NSInteger               requestDeviceIdCount;   //重新请求设备ID次数，超过10次，提示连接失败
//设备版本
@property (nonatomic)        BOOL                    didRequestDeviceVersion;   //请求设备版本
@property (nonatomic)        NSInteger               requestDeviceVersionCount;   //重新请求设备版本次数，超过10次，提示连接失败
//设备状态
@property (nonatomic)        BOOL                    didRequestDeviceState;//是否收到设备状态
@property (nonatomic)        NSInteger               requestDeviceStateCount;//重新请求设备状态次数，超过10次，提示连接失败

//日志
@property (nonatomic)        BOOL                    didRequestDeviceLog;//收到设备开始监测日志
@property (nonatomic)        NSInteger               requestDeviceLogCount;//请求日志的次数
@property (nonatomic, strong)NSData                  *lastLogData;//最近设备日志
@property (nonatomic, strong)NSTimer                 *requestLogTimer;//等待请求数据结尾 超过3s
//传输数据
@property (nonatomic, strong)NSMutableData           *recvData;//变长电流数据
@property (nonatomic, strong)NSData                  *lastRecvData;//最后收到的变长电流数据
@property (nonatomic)        NSUInteger              bcLength;//变长电流数据长度
@property (nonatomic, strong)NSMutableArray          *allRecvDataArr;//收到蓝牙的全部电流数据
@property (nonatomic, strong)NSTimer                 *recvDataWaitTimer;//收到电流数据等待3s，表示数据传输完了
//请求数据
@property (nonatomic)        BOOL                    isRequestData;   //是否在请求数据
@property (nonatomic)        NSInteger               requestStartIndex;//请求起始序号
@property (nonatomic)        NSInteger               requestEndIndex;//请求结束序号
@property (nonatomic, strong)NSMutableArray          *responseValueArr;//请求的返回电流值数组
@property (nonatomic, strong)NSMutableArray          *responseIndexArr;//请求数据序号数组
@property (nonatomic, strong)NSTimer                 *requestHandleWaitTimer;//等待请求数据结尾 超过3s


//倒计时
@property (nonatomic)        NSInteger              countDownTime;//倒计时 时间
@property (nonatomic, strong)NSTimer                *countDownTimer;//倒计时 定时器


//上传数据
@property (nonatomic)        NSInteger              referenceValue;//参比值

@property (nonatomic,strong) BSMainObj              *defBSM;
@end

@implementation HomeVC


#pragma mark - 初始化

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self initView];
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -initView

-(void)initView
{
    self.view.backgroundColor = kBacColor;
    self.title = kLocal(@"Blood sugar");
    self.tabBarItem.image = [UIImage imageNamed:@"bloodsugar_grey"];
    self.tabBarItem.selectedImage = [UIImage imageNamed:@"bloodsugar_blue"];
    
    _mainV = [[HomeMainV alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-kTabBarHeight)];
    [self.view addSubview:_mainV];//主页面
    
    [_mainV.userBtn addTarget:self action:@selector(BtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [_mainV.BLEBtn addTarget:self action:@selector(BtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [_mainV.currentV.canbi addTarget:self action:@selector(BtnClick:) forControlEvents:UIControlEventTouchUpInside];
    _mainV.ratView.delegate = self;
 }


-(void)BtnClick:(UIButton *)Btn
{
    kDebug(@"点击%ld按钮",(long)Btn.tag);
    switch (Btn.tag) {
        case 1:
        {
            [_leftU show];
        }
            break;
        case 2:
        {
           
        }
            break;
        case 3:
        {
             [_rightB show];
//            if (_didBindDevice) {
//                UIAlertView *alv = [[UIAlertView alloc] initWithTitle:@"警告" message:@"确定要停止监测吗？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"停止监测", nil];
//                alv.tag = 5000;
//                [alv show];
//            }else{
//                
//            }
        }
            break;
        case 100://canbi
        {
            [self enterReferenceValueWithCancelOptions:YES descriptionText:nil];
            [_mainV.currentV.canbi setEnabled:NO];
        }
            break;
        default:
            break;
    }
}

-(void)RatViewBtnClick:(UIButton*)Btn
{
    int day = Btn.tag;
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    int index = [def integerForKey:kLastHandleIndex];
    if (index && _defBSM.startMeasureDate) {
        
        int ofsetIndex = [self getOfsetIndexFromStartMeasureDate];
        NSDate *date = [NSDate dateWithTimeInterval:(((day*480) - ofsetIndex) * 180) sinceDate:_defBSM.startMeasureDate];
        
        [_mainV.ratView refreshViewWithCount:day andDate:date];
        NSArray *array;
        if (day == 0) {
            array = [self getBSDataArrFromDBWithStartIndex:1 toIndex:480 - ofsetIndex];
        }else{
            array = [self getBSDataArrFromDBWithStartIndex: (day*480) - ofsetIndex toIndex:((day+1)*480) - ofsetIndex];
        }
        
        NSMutableArray *arr = [NSMutableArray array];
        for (BSDataObj *b in array) {
            NSNumber *numY = [NSNumber numberWithFloat:b.BSValue];
            [arr addObject:numY];
        }
        
        float offSet;
        if (day > 0) {
            offSet = 0;
        }else{
            offSet = ofsetIndex;
        }
        
        NSNumber *offSetNum = [NSNumber numberWithFloat:offSet];
        [_mainV.chartV refreshViewWithDataDic:[NSDictionary dictionaryWithObjects:@[arr,offSetNum] forKeys:@[kGraphData,kOffSet]]];
    }
}


- (void)refreshChartViewAndRatView
{

    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    int index = [def integerForKey:kLastHandleIndex];
    if (index) {
        
        NSDate *baseDate = _defBSM.startMeasureDate;
        
        if(baseDate){
            kDebug(@"刷新视图-----------------------");
            NSDate *date = [NSDate dateWithTimeInterval:(index * 180) sinceDate:baseDate];
            
            int ofsetIndex= [self  getOfsetIndexFromStartMeasureDate];
            int indexAll = index + ofsetIndex;
            int day = 0;
            if (indexAll <= 480) {
            
            }else{
                day = (indexAll / 480) ;
                
            }
            _mainV.ratView.Count = day;
            [_mainV.ratView refreshViewWithCount:day andDate:date];
            
            NSArray *array;
            if (day == 0) {
                array = [self getBSDataArrFromDBWithStartIndex:1 toIndex:index];
            }else{
                array = [self getBSDataArrFromDBWithStartIndex: (day*480) - ofsetIndex toIndex:index];
            }
            
            
            NSMutableArray *arr = [NSMutableArray array];
            for (BSDataObj *b in array) {
                NSNumber *numY = [NSNumber numberWithFloat:b.BSValue];
                [arr addObject:numY];
            }
            
            float offSet;
            if (indexAll > 480) {
                offSet = 0;
            }else{
                offSet = ofsetIndex;
            }
            
            NSNumber *offSetNum = [NSNumber numberWithFloat:offSet];
            [_mainV.chartV refreshViewWithDataDic:[NSDictionary dictionaryWithObjects:@[arr,offSetNum] forKeys:@[kGraphData,kOffSet]]];
        }else{//若没有开始检测日志，已经绑定，则请求日志
    
            if (!_didBindDevice)//如果没有绑定，则返回
                return;
            
            _didRequestDeviceLog = NO;
            _requestDeviceLogCount = 0;
            [self requestDeviceLog];
        }
    }

}

#pragma mark -initData

-(void)initData
{
    _manage = [[CBCentralManager alloc]initWithDelegate:self queue:nil];
    _periArr = [NSMutableArray array];
    
    _leftU = [[UserVC alloc]init];
    _leftU.sideBarWidth = 200;
    _leftU.delegate = self;
    _leftU.translucentStyle = UIBarStyleBlackTranslucent;
    _leftU.tag = 0;
    
    // Create Right SideBar
    _rightB = [[BLEVC alloc] initWithDirection:YES];
//    _rightB.manage = _manage;
//    _rightB.periArr = _periArr;
    _rightB.sideBarWidth = 200;
    _rightB.delegate = self;
    _rightB.translucentStyle = UIBarStyleBlack;
    _rightB.tag = 1;
    
    // Add PanGesture to Show SideBar by PanGesture
    UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGesture:)];
    [self.view addGestureRecognizer:panGestureRecognizer];
    
    
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
   
    //参比
    NSArray *refArray = [def arrayForKey:kReferenceArray];
    [_mainV.currentV.canbi setTitle:[NSString stringWithFormat:kLocal(@"canbi"),refArray.count] forState:UIControlStateNormal];
    
    
   
    //刷新图表
    [NSTimer scheduledTimerWithTimeInterval:180 target:self selector:@selector(refreshChartViewAndRatView) userInfo:nil repeats:YES];
    
    // 监测网络情况
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        kDebug(@"%d", status);
    }];
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
    
    _defBSM = [[BSMainObj alloc]init];
    _defBSM.userID = [def integerForKey:kLastUserID];
    _defBSM.deviceID = [def stringForKey:kLastDeviceID];
    _defBSM.sensorID = [def stringForKey:kLastSensorID];
    _defBSM.startMeasureDate = [def objectForKey:kLastStartMeasureDate];
    _defBSM.sensorInitDate = [def objectForKey:kLastSensorInitDate];

    [self handleAllrCurrentValueFromDB];

    [NSTimer scheduledTimerWithTimeInterval:20 target:self selector:@selector(checkOutStartMeasureDate:) userInfo:nil repeats:YES];
    
}

-(void)checkOutStartMeasureDate:(NSTimer *)timer
{
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    int index = [def integerForKey:kLastHandleIndex];
    if (index) {
        
        if(_defBSM.startMeasureDate){//若没有开始检测日志，已经绑定，则请求日志
            
            if (!_didBindDevice)//如果没有绑定，则返回
                return;
            _didRequestDeviceLog = NO;
            _requestDeviceLogCount = 0;
            [self requestDeviceLog];
        }else{
            [timer invalidate];
            timer = nil;
        }
    }
}


//手势
- (void)handlePanGesture:(UIPanGestureRecognizer *)recognizer
{
    
    // if you have left and right sidebar, you can control the pan gesture by start point.
    if (recognizer.state == UIGestureRecognizerStateBegan) {
        CGPoint startPoint = [recognizer locationInView:self.view];
        
        // Left SideBar
        if (startPoint.x < self.view.bounds.size.width / 2.0) {
            _leftU.isCurrentPanGestureTarget = YES;
        }
        // Right SideBar
        else {
            _rightB.isCurrentPanGestureTarget = YES;
        }
    }
    
    [_leftU handlePanGestureToShow:recognizer inView:self.view];
    [_rightB handlePanGestureToShow:recognizer inView:self.view];
    
}


#pragma mark - 向蓝牙发送数据

//对设备写数据
-(void)writeValue:(NSData *)aData{
    [_peri writeValue:aData forCharacteristic:_cha type:CBCharacteristicWriteWithoutResponse];//不带反馈
}

//停止检测，断开设备连接
- (void)disConnectDevice
{
    Byte byte[] = {0x0f,0xa4,0x00,0x00,0x00,0x00,0xab};//停止检测
    NSData *adata = [NSData dataWithBytes:byte length:sizeof(byte)/sizeof(Byte)];
    [self writeValue:adata];
    kDebug(@"发送停止检测指令:%@",adata);
}

//数据确认指令 0xae
- (void)sendConfirmInstruction
{
    Byte byte[] = {0x0f,0xae,0x00,0x00,0x00,0x00,0xa1};
    NSData *adata = [NSData dataWithBytes:byte length:sizeof(byte)/sizeof(Byte)];
    [self writeValue:adata];
    kDebug(@"发送确认指令:%@",adata);
}

//时间同步 0xa0
- (void)syncTime
{
    if (_didSyncTime) {
        _syncTimeCount = 0;
    }else{
        if (_syncTimeCount > 10) {
            kDebug(@"同步时间10次失败");
            _syncTimeCount = 0;
            
            [_manage cancelPeripheralConnection:_peri];//断开蓝牙
        }else{
            _syncTimeCount ++;
            
            long long timeInterval = [[NSDate date] timeIntervalSince1970];
            Byte high1 = timeInterval/0x1000000;
            Byte high2 = (timeInterval%0x1000000)/0x10000;
            Byte high3 = ((timeInterval%0x1000000)%0x10000)/0x100;
            Byte high4 = ((timeInterval%0x1000000)%0x10000)%0x100;
            
            Byte data[] = {0x0f,0xa0,high4,high3,high2,high1};
            Byte result = [self getVerifyFromData:data andLength:6];
            Byte byte[] = {0x0f,0xa0,high4,high3,high2,high1,result};
            
            NSData *adata = [NSData dataWithBytes:byte length:sizeof(byte)/sizeof(Byte)];
            [self writeValue:adata];
            kDebug(@"发送时间同步指令:%@",adata);
            [self performSelector:@selector(syncTime) withObject:nil afterDelay:1];//未成功延迟1s后再次发送
        }
    }
    
}


//密码绑定设备
- (void)bindDevice
{
    if (_didBindDevice) {
        _bindDeviceCount = 0;
        
    }else{
        if (_bindDeviceCount > 10) {
            kDebug(@"绑定失败");
            _bindDeviceCount = 0;
            
            _syncTimeCount = 0;
            _didSyncTime = NO;
            [self syncTime];//重新时间同步
        }else{
            
            _bindDeviceCount ++;
            int passwordValue = [_devicePassword intValue];
            Byte password1 = passwordValue / 0x100;
            Byte password2 = passwordValue % 0x100;
            
            Byte data[] = {0x0f,0xa1,password2,password1,0x00,0x00};
            Byte result = [self getVerifyFromData:data andLength:6];
            Byte byte[] = {0x0f,0xa1,password2,password1,0x00,0x00,result};
            
            NSData *adata = [NSData dataWithBytes:byte length:sizeof(byte)/sizeof(Byte)];
            [self writeValue:adata];
            kDebug(@"发送绑定指令:%@",adata);
//            [self performSelector:@selector(bindDevice) withObject:nil afterDelay:1.f];//未成功延迟1s后再次发送
        }
    }
}



//获取设备id
- (void)requestDeviceId
{
    if (_didRequestDeviceId) {
        _requestDeviceIdCount = 0;
    }else{
        if (_requestDeviceIdCount > 10) {
            kDebug(@"请求设备ID失败");
            _requestDeviceIdCount = 0;
            
            _syncTimeCount = 0;
            _didSyncTime = NO;
            [self syncTime];//重新时间同步
        }else{
            _requestDeviceIdCount ++;
            Byte byte[] = {0x0f,0xad,0x00,0x00,0x00,0x00,0xa2};
            NSData *adata = [NSData dataWithBytes:byte length:sizeof(byte)/sizeof(Byte)];
            [self writeValue:adata];
            kDebug(@"发送请求设备ID指令:%@",adata);
            [self performSelector:@selector(requestDeviceId) withObject:nil afterDelay:1.f];
        }
    }
}

//获取固件版本
- (void)requestDeviceVersion
{
    if (_didRequestDeviceVersion) {
        _requestDeviceVersionCount = 0;
    }else{
        if (_requestDeviceVersionCount > 10) {
            kDebug(@"请求设备版本失败");
            _requestDeviceVersionCount = 0;
            
            _syncTimeCount = 0;
            _didSyncTime = NO;
            [self syncTime];//重新时间同步
        }else{
            _requestDeviceVersionCount ++;
            Byte byte[] = {0x0f,0xab,0x00,0x00,0x00,0x00,0xa4};
            NSData *adata = [NSData dataWithBytes:byte length:sizeof(byte)/sizeof(Byte)];
            [self writeValue:adata];
            kDebug(@"发送请求设备版本指令:%@",adata);
            [self performSelector:@selector(requestDeviceVersion) withObject:nil afterDelay:1.f];
        }
    }
}


//获取设备状态
- (void)requestDeviceState
{
    if (_didRequestDeviceState) {
        _requestDeviceStateCount = 0;
    }else{
        if (_requestDeviceStateCount > 5) {
            kDebug(@"请求设备状态失败");
            _requestDeviceStateCount = 0;
            
            _syncTimeCount = 0;
            _didSyncTime = NO;
            [self syncTime];//重新时间同步
        }else{
            _requestDeviceStateCount ++;
            Byte byte[] = {0x0f,0xa8,0x00,0x00,0x00,0x00,0xa7};
            NSData *adata = [NSData dataWithBytes:byte length:sizeof(byte)/sizeof(Byte)];
            [self writeValue:adata];
            kDebug(@"发送请求状态指令:%@",adata);
            [self performSelector:@selector(requestDeviceState) withObject:nil afterDelay:1.f];
        }
    }
}

//获取设备日志
- (void)requestDeviceLog
{
    if(_didRequestDeviceLog){
        _requestDeviceLogCount = 0;
    }else{
        if (_requestDeviceLogCount > 5) {
            _requestDeviceStateCount = 0;
            
            _syncTimeCount = 0;
            _didSyncTime = NO;
            [self syncTime];//重新时间同步
        }else{
            _requestDeviceLogCount++;
            Byte byte[] = {0x0f,0xaa,0x00,0x00,0x00,0x00,0xa5};
            NSData *adata = [NSData dataWithBytes:byte length:sizeof(byte)/sizeof(Byte)];
            [self writeValue:adata];
            kDebug(@"发送请求设备日志指令:%@",adata);
            [self performSelector:@selector(requestDeviceLog) withObject:nil afterDelay:5.f];//获取日志时间比较久，要多等一会
        }
    }
}

-(void)requestDeviceData
{
    if (!_didBindDevice && _requestStartIndex > _requestEndIndex) {
        _isRequestData = NO;
    }else{
        [self requestDeviceDataFromIndex:_requestStartIndex toIndex:_requestEndIndex];
        [self performSelector:@selector(requestDeviceData) withObject:nil afterDelay:30];
    }
}

//请求某段数据
- (void)requestDeviceDataFromIndex:(int )fromIndex toIndex:(int )toIndex
{
    if(fromIndex > toIndex )
        return;
    kDebug(@"请求数据 %d --> %d",fromIndex ,toIndex);

    Byte data[] = {0x0f,0xa7,fromIndex%0x100,fromIndex/0x100,toIndex%0x100,toIndex/0x100};
    Byte result = [self getVerifyFromData:data andLength:6];
    Byte data2[] = {0x0f,0xa7,fromIndex%0x100,fromIndex/0x100,toIndex%0x100,toIndex/0x100,result};
    NSData *adata = [NSData dataWithBytes:data2 length:sizeof(data2)/sizeof(Byte)];
    [self writeValue:adata];
    kDebug(@"发送请求设备数据指令:%@",adata);
}


#pragma mark -  蓝牙代理函数 CBCentralManagerDelegate,CBPeripheralDelegate
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    switch (central.state) {
        case CBCentralManagerStatePoweredOn:
            break;
        case CBCentralManagerStatePoweredOff:
            break;
        default:
            break;
    }
}

//发现周边设备
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
    kDebug(@"RSSI=%@ peripheral=%@",RSSI,peripheral.name);
    if (![_periArr containsObject:peripheral]) {
        [_periArr addObject:peripheral];
    }
    
    NSString *lastDevice = [[NSUserDefaults standardUserDefaults] stringForKey:kLastBindDevice];
    
    if (lastDevice && [peripheral.name isEqualToString:lastDevice]) {//自动连接设备
        [_manage stopScan];
        [_manage connectPeripheral:peripheral options:nil];
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
//            
//        });
    }
    
}

//断开连接通知
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    _didBindDevice  = NO;
    if (error) {//异常断开
        kDebug(@"连接断开出错: %@",error);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
            [central connectPeripheral:peripheral options:nil];//重连
        });
    }else{
        
    }
}

//连接设备成功
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    // Clears the data that we may already have
    kDebug(@"已连接蓝牙:%@",peripheral.name);
    
    _peri = peripheral;
    [peripheral setDelegate:self];
    [peripheral discoverServices:@[[CBUUID UUIDWithString:kServiceUUID]]];
    
}

//发现设备服务
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
    if (error) {
        kDebug(@"发现服务出错: %@", [error localizedDescription]);
        return;
    }
    for (CBService *s in peripheral.services) {
        if ([s.UUID isEqual:[CBUUID UUIDWithString:kServiceUUID]]) {
            [peripheral discoverCharacteristics:@[[CBUUID UUIDWithString:kCharacteristicUUID]] forService:s];
        }
    }
}

//发现特征服务
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService: (CBService *)service error:(NSError *)error
{
    if (error) {
        kDebug(@"发现特性出错: %@", [error localizedDescription]);
        return;
    }
    if ([service.UUID isEqual:[CBUUID UUIDWithString:kServiceUUID]]) {
        for (CBCharacteristic *cbcts in service.characteristics) {
            if ([cbcts.UUID isEqual:[CBUUID UUIDWithString:kCharacteristicUUID]]) {
                _cha = cbcts;
                [peripheral setNotifyValue:YES forCharacteristic:cbcts];
            }
        }
    }
}

//设置监听代理
- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    if (error) {
        kDebug(@"设置监听出错: %@", error.localizedDescription);
        return;
    }
    if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:kCharacteristicUUID]]) {
        if (characteristic.isNotifying) {//开始监听
            
            _didBindDevice = NO;
            _bindDeviceCount = 0;
            if (_devicePassword) {//若有密码，直接绑定
                [self bindDevice];
                
            }else{//若无密码，发送时间同步
                _didSyncTime = NO;
                _syncTimeCount = 0;
                [self syncTime];
            }
        }else {//停止监听，断开设备连接
            [_manage cancelPeripheralConnection:peripheral];
        }
    }
}

//收到蓝牙设备返回的值
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    if (error) {
        kDebug(@"收到数据出错: %@", [error localizedDescription]);
        return;
    }
    kDebug(@"收到%d数据:%@",(int)characteristic.value.length,characteristic.value);
    Byte *temp = (Byte *)[characteristic.value bytes];
    NSUInteger length = characteristic.value.length;
    
    if ((length == 7|| length == 9)) {
        
        BOOL ret = [self verifyData:temp andLength:length];//校验
        if (!ret){
            kDebug(@"校验数据或者日志出错");
            return;
        }
        if(temp[0] != 0x1f){
            kDebug(@"数据错误-0x1f");
            return;
        }
        if (length == 7) {//普通指令
            [self handleData:temp];
        }
        else if (length == 9) {//处理日志指令
            [self handleLogData:temp];
        }
    }
    else{//长度为偶数 //变长数据处理
        
        if (temp[0] == 0x1f && temp[1] == 0xa6) {
            _bcLength = temp[2] + 4;
            _recvData = [NSMutableData data];
        }
        
        [_recvData appendData:characteristic.value];
        
        if (_recvData.length >= _bcLength && _bcLength > 0) {
            [self sendConfirmInstruction];//发送确认指令
            
            NSData * data = [_recvData subdataWithRange:NSMakeRange(0, _bcLength)];
            Byte *bctemp = (Byte *)[data bytes];
            
            BOOL ret = [self verifyData:bctemp andLength:_bcLength];//校验
            if (!ret) {
                kDebug(@"血糖数据校验失败，返回的是错误的数据");
                return;
            }
            
            if ([_lastRecvData isEqual:data]){
                kDebug(@"前后2次血糖数据一样，弃用");
                return;
            }
            _lastRecvData = data;
            if (!_allRecvDataArr) {
                _allRecvDataArr = [NSMutableArray array];
            }
            [_allRecvDataArr addObject:_lastRecvData];
            
            if(_recvData.length > _bcLength){//如果是拼包
                kDebug(@"出现拼包了------");
                NSData *newD = [_recvData subdataWithRange:NSMakeRange(_bcLength, _recvData.length - _bcLength)];
                Byte *newT = (Byte*)[newD bytes];
                if (newT[0] == 0x1f && newT[1] == 0xa6) {
                    _bcLength = temp[2] + 4;
                    _recvData = [NSMutableData dataWithData:newD];
                }
            }
            
            //3s没有收到数据,表示数据已经全部接收完则执行数据处理
            if (_recvDataWaitTimer) {
                [_recvDataWaitTimer invalidate];
                _recvDataWaitTimer = nil;
            }
            _recvDataWaitTimer = [NSTimer scheduledTimerWithTimeInterval:3.0f target:self selector:@selector(handleVariableData) userInfo:nil repeats:NO];
            
        }
        
    }
}

#pragma mark - 蓝牙数据，日志处理


- (void)handleData:(Byte *)temp
{
    if (temp[1]==0xa0) {//同步时间反馈------
        _didSyncTime = YES;
        _syncTimeCount = 0;
        
        _didBindDevice = NO;
        _bindDeviceCount = 0;
        if (_devicePassword) {
            [self bindDevice];
        }
        
        _bindAlert = [[UIAlertView alloc] initWithTitle:nil
                                                      message:kLocal(@"请输入绑定密码")
                                                     delegate:self
                                            cancelButtonTitle:kLocal(@"No")
                                            otherButtonTitles:kLocal(@"Yes"), nil];
        _bindAlert.alertViewStyle = UIAlertViewStylePlainTextInput;
        _bindAlert.tag = 3001;
        [_bindAlert show];
    }
    else if (temp[1] ==0xa1) {//绑定设备反馈
        if (temp[2] == 0xaa) {//成功------
            
            _didBindDevice  = YES;
            _bindDeviceCount = 0;
            
            //视图
            [_bindAlert dismissWithClickedButtonIndex:0 animated:NO];
            _bindAlert = nil;
            
            NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
            //存储已经绑定过的设备
            [def setObject:_peri.name forKey:kLastBindDevice];
            
            //获取设备和针头信息
            NSString *deviceIDStr = [_peri.name substringWithRange:NSMakeRange(5, 8)];
            int sid = (temp[5]<< 16) + (temp[4]<<8) +temp[3];
            NSString *sensorIDStr = [NSString stringWithFormat:@"%d",sid];
            
            if (![_defBSM.deviceID isEqualToString:deviceIDStr] ||
                ![_defBSM.sensorID isEqualToString:sensorIDStr]) {//设备ID 或者 针头ID不一样，说明换针头了
                
                BGC_Init();
                
                //存储
                
                [def removeObjectForKey:kReferenceArray];
                [def removeObjectForKey:kLastHandleIndex];
                [def removeObjectForKey:kLastHandleValue];
                
                //视图
                [_mainV.currentV.canbi setTitle:[NSString stringWithFormat:kLocal(@"canbi"),0] forState:UIControlStateNormal];
                
                NSMutableArray *defBSMainObjArr = [[DBManage sharedManager] queryDataFromTable:kBSMainTable andConditions:nil];
               
                BOOL needInsert = YES;
                
                for (BSMainObj *bsm in defBSMainObjArr) {
                    NSString *dev = bsm.deviceID;
                    if ([dev isEqualToString:deviceIDStr]) {//找设备ID
                        NSString *sen = bsm.sensorID;
                        if ([sen isEqualToString:sensorIDStr]) {//找传感器ID
                            kDebug(@"以前连接过的旧针头");
                            _defBSM = bsm;
                            needInsert = NO;
                        }
                        break;
                    }
                }
                if (needInsert) {//第一次连接，或者是新针头
                    kDebug(@"新针头");
                    _defBSM = [[BSMainObj alloc]init];
                    _defBSM.userID = [def integerForKey:kNetUserID];//用户ID
                    _defBSM.deviceID = deviceIDStr;//设备ID
                    _defBSM.sensorID = sensorIDStr;//传感器ID
                    _defBSM.sensorInitDate = nil;
                    _defBSM.startMeasureDate = nil;
                    
                    [[DBManage sharedManager] insertData:_defBSM andTable:kBSMainTable];//加入数据库

                }
                [def setInteger:_defBSM.userID forKey:kLastUserID];
                [def setObject:_defBSM.deviceID forKey:kLastDeviceID];
                [def setObject:_defBSM.sensorID forKey:kLastSensorID];
                [def setObject:_defBSM.startMeasureDate forKey:kLastStartMeasureDate];
                [def setObject:_defBSM.sensorInitDate forKey:kLastSensorInitDate];
            }
            [def synchronize];
            
            _didRequestDeviceVersion = NO;
            _requestDeviceVersionCount = 0;
            [self requestDeviceVersion];
            

        } else {//失败------0x55或者其他
            _didBindDevice = NO;
            if (!_bindAlert) {
                _bindAlert = [[UIAlertView alloc] initWithTitle:nil
                                                        message:kLocal(@"未绑定，请重新输入密码绑定")
                                                       delegate:self
                                              cancelButtonTitle:kLocal(@"No")
                                              otherButtonTitles:kLocal(@"Yes"), nil];
                _bindAlert.alertViewStyle = UIAlertViewStylePlainTextInput;
                _bindAlert.tag = 3001;
                [_bindAlert show];
            }
        }
    }
    else if(temp[1] == 0xab){//设备版本反馈------
        
        _didRequestDeviceVersion = YES;
        _requestDeviceVersionCount = 0;
        
        NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
        NSString *version = [NSString stringWithFormat:@"V%d.%d.%d",temp[4],temp[3],temp[2]];
        [def setObject:version forKey:@"DevVersion"];
        [def synchronize];
        kDebug(@"版本号====%@",version);
        
        _didRequestDeviceState = NO;
        _requestDeviceStateCount = 0;
        [self requestDeviceState];
        
    } else if (temp[1]==0xa4) {//结束监测反馈------
        
        [_manage cancelPeripheralConnection:_peri];
        
        if (self.countDownTimer) {
            [self.countDownTimer invalidate];
            self.countDownTimer = nil;
        }
        _countDownTime = -1;
        _didBindDevice = NO;
        
        _mainV.currentV.stateLabel.text = @"监测结束";
        _mainV.currentV.bspro.z = 0;
    }
    else if (temp[1]==0xa9) {//发射器工作状态反馈------4种
        [self sendConfirmInstruction];//发送确认指令
        
        _didRequestDeviceState = YES;
        _requestDeviceStateCount = 0;
        
        //temp[2] 表示传感器的工作状态，状态只有1种，
        Byte byte2bit1Value = temp[2] & (0x01<<1);
        Byte byte2bit2Value = temp[2] & (0x01<<2);
        Byte byte2bit3Value = temp[2] & (0x01<<3);
        Byte byte2bit4Value = temp[2] & (0x01<<4);
        
        if (byte2bit4Value==0x10) {//监测结束
            
            if (_countDownTimer) {
                [_countDownTimer invalidate];
                _countDownTimer = nil;
            }
            _countDownTime = -1;
            _mainV.currentV.bspro.z = 0;
            _mainV.currentV.stateLabel.text = @"监测结束";
            
            int last = [[NSUserDefaults standardUserDefaults] integerForKey:kLastHandleIndex];
            if(last < 3361){
                _requestStartIndex = last;
                _requestEndIndex = 3361;
                _isRequestData = YES;
                [self requestDeviceData];
            }
        }
        else if (byte2bit4Value==0x00 && byte2bit3Value==0x08) {//监测中

            if (_countDownTimer) {
                [_countDownTimer invalidate];
                _countDownTimer = nil;
            }
            _countDownTime = -1;
            _mainV.currentV.stateLabel.text = @"监测中";
        }
        else if (byte2bit4Value==0x00 && byte2bit3Value==0x00 && byte2bit2Value==0x04) {//数据初始化(3小时，传感器初始化结束日志)
           
            if (_countDownTimer) {
                [_countDownTimer invalidate];
                _countDownTimer = nil;
            }
            _mainV.currentV.stateLabel.text = @"数据初始化";
            _mainV.currentV.bspro.style = ProgressBarStyleCountDown180;
            _mainV.currentV.bspro.z = 0;
            NSDate *startDate = _defBSM.startMeasureDate;
            if (startDate) {
                NSTimeInterval timeInterval = [[NSDate date] timeIntervalSinceDate:startDate];
                if (timeInterval >= 0 && timeInterval <= 3*60*60) {
                    _countDownTime = (3*60*60 - timeInterval)/60;
                    _mainV.currentV.bspro.style = ProgressBarStyleCountDown180;
                    _mainV.currentV.bspro.z = _countDownTime;
                    _countDownTimer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(showCountDownTimeWithTimer:) userInfo:[NSNumber numberWithInt:ProgressBarStyleCountDown180] repeats:YES];
                }
            }
            else {
                kDebug(@"数据初始化--3小时请求日志");
                [self requestDeviceLog];
            }
        }
        else if (byte2bit4Value==0x00 && byte2bit3Value==0x00 && byte2bit2Value==0x00 && byte2bit1Value==0x02) {
            //传感器初始化(7分钟，传感器初始化开始日志)
            if (_countDownTimer) {
                [_countDownTimer invalidate];
                _countDownTimer = nil;
            }
            _mainV.currentV.stateLabel.text = @"传感器初始化";
            _mainV.currentV.bspro.style = ProgressBarStyleCountDown7;
            _mainV.currentV.bspro.z = 0;
            NSDate *initDate = _defBSM.sensorInitDate;
            if (initDate) {
                NSTimeInterval timeInterval = [[NSDate date] timeIntervalSinceDate:initDate];
                if (timeInterval >= 0 && timeInterval <= 8*60) {
                    _countDownTime = (8*60 - timeInterval);
                    _mainV.currentV.bspro.style = ProgressBarStyleCountDown7;
                    _mainV.currentV.bspro.z = 0;
                    _countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(showCountDownTimeWithTimer:) userInfo:[NSNumber numberWithInt:ProgressBarStyleCountDown7] repeats:YES];
                }
            }
            else {//否则，请求设备日志信息
                kDebug(@"传感器初始化--8分钟请求日志");
                [self requestDeviceLog];
            }
        }
        
        //temp[3] 表示报警，可以同时有多重报警信息
        //通过bit位来判断传送了什么报警，所有的都要判断
        Byte byte3bit1Value = temp[3] & (0x01<<1);
        Byte byte3bit2Value = temp[3] & (0x01<<2);
        Byte byte3bit3Value = temp[3] & (0x01<<3);
        Byte byte3bit4Value = temp[3] & (0x01<<4);
        Byte byte3bit5Value = temp[3] & (0x01<<5);
        if (byte3bit1Value == 0x02) {//血糖电流过小警报
            [self showDeviceAlertWithType:0x01];
        }
        if (byte3bit2Value == 0x04) {//血糖电流过小警报
            [self showDeviceAlertWithType:0x02];
        }
        if (byte3bit3Value == 0x08) {//电量低警报
            [self showDeviceAlertWithType:0x03];
        }
        if (byte3bit4Value == 0x10) {//传感器已到期限警报
            [self showDeviceAlertWithType:0x04];
        }
        if (byte3bit5Value == 0x20) {//日志存储区已满报警
            [self showDeviceAlertWithType:0x05];
        }
    }

    
}

//处理日志数据
- (void)handleLogData:(Byte *)temp
{
    [self sendConfirmInstruction];
    
    //3s没有收到日志,表示日志已经全部接收完则 请求状态
    if (_requestLogTimer) {
        [_requestLogTimer invalidate];
        _requestLogTimer = nil;
    }
    _didRequestDeviceState = NO;
    _requestDeviceStateCount = 0;
    _requestLogTimer = [NSTimer scheduledTimerWithTimeInterval:3.0f target:self selector:@selector(requestDeviceState) userInfo:nil repeats:NO];
    
    NSData *tempData = [NSData dataWithBytes:temp length:9];
    if ([tempData isEqual:_lastLogData]) {
        kDebug(@"和上次返回日志一样，丢弃，tempData = %@",tempData);
        return;
    }
    
    int     lType  = temp[1];//日志类型
    NSDate  *lDate = [self getLogDateFromData:temp];//日志时间
    
    //(byteData[1]) 0-空日志,1-绑定成功日志,2-时间同步日志,3-传感器更换日志,4-传感器初始化开始日志,5-传感器初始化结束日志,6-开始检测日志,7-结束检测日志,8-改密日志,9-掉电日志,15-报警汇总日志
    //byteData[2] 1-血糖电流过小日志,2-血糖电流过大日志,3-发射器电量低日志,4-传感器已到期限日志,5-日志存储空间已满日志,6-传输失败日志

    //    kDebug(@"日志类型:%d,发生时间:%@",lType,lDate);
    
    if (lType == 4 || lType == 6){//4-传感器初始化开始日志//6-开始检测日志
        _didRequestDeviceLog = YES;
        _requestDeviceLogCount  = 0;
        NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
        if (lType == 4) {
            kDebug(@"传感器初始化开始日志 ========= %@",[NSString stringFromDate:lDate]);
            _defBSM.sensorInitDate = lDate;
            [def setObject:lDate forKey:kLastSensorInitDate];
        }else{
            kDebug(@"开始检测日志 ********* %@",[NSString stringFromDate:lDate]);
            _defBSM.startMeasureDate = lDate;
            [def setObject:lDate forKey:kLastStartMeasureDate];
        }
        [def synchronize];
    
    }else if(lType == 15){
        
    }
    
    _lastLogData = tempData;
    
    
}

//处理全部的变长血糖
- (void)handleVariableData
{
    Byte *tmpStart = (Byte*)[_allRecvDataArr[0] bytes];
    Byte *tmpEnd = (Byte*)[_allRecvDataArr[_allRecvDataArr.count -1] bytes];
    
    int startIndex = (tmpStart[4]<<8) + tmpStart[3];
    int endIndex = (tmpEnd[6]<<8) + tmpEnd[5];
    
    int dataNum = endIndex - startIndex + 1;
    if (startIndex > endIndex) {
        kDebug(@"数据乱序，丢弃");
        _allRecvDataArr = nil;//处理完清空全部的血糖数据
        return;
    }
    
    NSMutableData *data = [NSMutableData data];
    for (int i = 0; i < _allRecvDataArr.count; i++){
        NSData *tmpdata = _allRecvDataArr[i];
        [data appendData:[tmpdata subdataWithRange:NSMakeRange(7, tmpdata.length - 8)]];
    }
    
    if (dataNum == data.length/2) {//数据全部接收到，且连续
        kDebug(@"全部接收完成,且连续,总共 %d 个, %d-->%d",dataNum,startIndex,endIndex);
        
        NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
        
        Byte *bcTmp = (Byte*)[data bytes];
        
        for (int index = startIndex; index <= endIndex; index++ ) {
            
            int currentValue  = (bcTmp[2*(index-startIndex)+1]<<8)+bcTmp[2*(index-startIndex)];
            

            
            if (!_isRequestData) {//非请求数据时，正常情况下，处理血糖数据
                
                if (index == endIndex && index >=60 && index <=3361) {//判断参比值输入
                    
                    NSArray *refArray = [def objectForKey:kReferenceArray];
                    if (refArray && refArray.count > 0) {
                        int refCount = refArray.count;
                        int reflastIndex = [[[refArray lastObject] objectForKey:kReferenceIndex ] intValue];
                        
                        if (refCount < 4){
                            if (index - reflastIndex >= (refCount+1) * 60) {
                                [self enterReferenceValueWithCancelOptions:YES descriptionText:nil];
                            }
                            
                        }else{
                            if (index - reflastIndex >= 4 * 60) {
                                [self enterReferenceValueWithCancelOptions:YES descriptionText:nil];
                            }
                        }
                        
                    }else{
                        [self enterReferenceValueWithCancelOptions:NO descriptionText:nil];//不可以取消
                    }
                }
                
                int  last = [def integerForKey:kLastHandleIndex];
                
                if(index == (last + 1))//数据连续
                {
                    
                    float bsvalue = [self handleDataWithCurrentValue:currentValue andIndex:index isDB:NO];//处理正常3分钟血糖数据
                    if (index > 60) {
                        if (_countDownTimer) {
                            [_countDownTimer invalidate];
                            _countDownTimer = nil;
                        }
                        _countDownTime = -1;
                        _mainV.currentV.bspro.style = ProgressBarStyleBlood;
                        _mainV.currentV.bspro.z = bsvalue;
                    }
                    
                    [def setInteger:index forKey:kLastHandleIndex];
                    [def setInteger:currentValue forKey:kLastHandleValue];
                    [self saveDataToDBWithCurrentValue:currentValue andIndex:index andBSValue:bsvalue];//将数据存储到数据库
                    
                }
                else{
                    
                    _requestStartIndex = last + 1;//上一次正常处理的数据序号 + 1
                    _requestEndIndex   = endIndex;
                    _isRequestData = YES;
                    [self requestDeviceData];
                    break;
                }

            }
            else {

                if (index >= _requestStartIndex && index <= _requestEndIndex) {//请求的电流数据
                    if (!_responseIndexArr) {
                        _responseIndexArr = [NSMutableArray array];
                    }
                    if (![_responseIndexArr containsObject:[NSNumber numberWithInt:index]]) {
                        [_responseIndexArr addObject:[NSNumber numberWithInt:index]];
                        if (!_responseValueArr) {
                            _responseValueArr = [NSMutableArray array];
                        }
                        [_responseValueArr addObject:[NSNumber numberWithInt:currentValue]];
                        
                        if (_requestHandleWaitTimer) {
                            [_requestHandleWaitTimer invalidate];
                            _requestHandleWaitTimer = nil;
                        }
                        //3s还没有请求数据来，表示请求数据接收完，但没有收到结束序号
                        _requestHandleWaitTimer = [NSTimer scheduledTimerWithTimeInterval:3.0f target:self selector:@selector(handleRequestCurrentData) userInfo:nil repeats:NO];
                    }
                    else {
                        kDebug(@"数据已经在请求的数据,index : %d",index);
                    }
                }else{//请求电流数据时，不处理正常血糖数据
                    
                    if (!_responseValueArr) {
                        kDebug(@"请求电流数据时,不处理正常血糖数据,index : %d",endIndex);
//                        _requestEndIndex   = endIndex;
//                        _isRequestData = YES;
//                        [self requestDeviceData];
//                        break;
                    }
                }
            }
        }
        
        [def synchronize];
        
    }else{//如果不连续，则请求这段数据（数据中间丢失）
        kDebug(@"全部接收完成,不连续，则请求 %d 个, %d-->%d",dataNum,startIndex,endIndex);
        [self requestDeviceDataFromIndex:startIndex toIndex:endIndex];
    }
    _allRecvDataArr = nil;//处理完清空全部的血糖数据
}

//计算请求或者正常血糖值
- (float)handleDataWithCurrentValue:(int )currentValue andIndex:(int)currentIndex isDB:(BOOL)isDB
{
    float bsvalue;
    if (isDB) {//如果是数据库则需要输入参比
        if (currentIndex >= 60) {
            //判断当前序号的电流是否 有给 参比值
            NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
            NSArray *refArray = [def objectForKey:kReferenceArray ];
            for (NSDictionary *dic in refArray) {
                int index2 = [[dic objectForKey:kReferenceIndex ] intValue];
                if (currentIndex == index2) {
                    int ref = [[dic objectForKey:kReferenceKey ] intValue];
                    [self enterReferenceWithValue:ref shouldSaveReferenceValue:NO];
                    break;
                }
            }
        }
    }
    
    _sConvertResult_t convert_result;
    int rslt = BGC_InputCurrent(currentValue, &convert_result);
    
    if ((rslt == BGC_OK) && (convert_result.state == BGC_OK)) {
        bsvalue = convert_result.bg / 1000.0f;
        
        if (rslt == BGC_OK && (convert_result.trend == BGC_TREND_SHARPRISE || convert_result.trend == BGC_TREND_SHARPFALL)) {
            //            [self postLocalNotificationWithAlertType:1];
        }
    }
    else {
        
        bsvalue = 0.0;
    }
//    kDebug(@"电流 %d,血糖 %.1f,序号 %d",currentValue,bsvalue,currentIndex);
//    kDebug(@"状态%d,血糖%d,K值%d,趋势%d,背景%d,index = %d",convert_result.state,convert_result.bg,convert_result.K,convert_result.trend,convert_result.Backgroud,currentIndex);
    return bsvalue;
    
}


//处理请求返回的血糖电流数据
//如果中间有数据缺失，例如100——120，则需从设备请求100-120这段数据
//并从本地数据库中拿出1-100的数据，再从头到尾处理一遍，才能得出100-120这段时间内正确的血糖值
- (void)handleRequestCurrentData
{
    kDebug(@"--------开始处理主动请求数据-----个数%d--------",_responseValueArr.count);
    
    for (int b = 0; b < _responseValueArr.count; b++) {
        
        int currentIndex = [[_responseIndexArr objectAtIndex:b] intValue];
        int currentValue = [[_responseValueArr objectAtIndex:b] intValue];
        
        float value = [self handleDataWithCurrentValue:currentValue andIndex:currentIndex isDB:NO];;//血糖数据
        [self saveDataToDBWithCurrentValue:currentValue andIndex:currentIndex andBSValue:value];
        
    }
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    [def setInteger:[[_responseIndexArr lastObject] integerValue] forKey:kLastHandleIndex];//最近处理的序号
    [def setInteger:[[_responseValueArr lastObject] integerValue] forKey:kLastHandleValue];//最近处理的电流值
    [def synchronize];
    
    int lastIndex = [[_responseIndexArr lastObject] intValue];
    _requestStartIndex = lastIndex +1;
    
    if (_requestStartIndex >= _requestEndIndex) {
        _responseIndexArr  = nil;
        _responseValueArr  = nil;
        _isRequestData = NO;//<-- 注意位置
    }
    
    if ( lastIndex >=60) {
        NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
        NSArray *refArray = [def objectForKey:kReferenceArray];
        
        if (refArray && refArray.count > 0) {
            NSUInteger refCount = refArray.count;
            int reflastIndex = [[[refArray lastObject] objectForKey:kReferenceIndex ] intValue];
            
            if (refCount < 4){
                if (lastIndex - reflastIndex >= (refCount+1) * 60) {
                    [self enterReferenceValueWithCancelOptions:YES descriptionText:nil];
                }
                
            }else{
                if (lastIndex - reflastIndex >= 4 * 60) {
                    [self enterReferenceValueWithCancelOptions:YES descriptionText:nil];
                }
            }
            
        }else{
            [self enterReferenceValueWithCancelOptions:NO descriptionText:nil];//不可以取消
        }
        
        if (_countDownTimer) {
            [_countDownTimer invalidate];
            _countDownTimer = nil;
        }
        _countDownTime = -1;
        _mainV.currentV.bspro.style = ProgressBarStyleBlood;
    }
    
    kDebug(@"--------主动请求数据处理完成-------------");
}


//从数据库中拿出所有数据，做从头检测处理
- (void)handleAllrCurrentValueFromDB
{
    kDebug(@"--------开始处理数据库血糖数据-------------");
    BGC_Init();
    NSArray *BSDataObjArray = [self getAllCurrentDataFromDB];
    for (BSDataObj *obj in BSDataObjArray) {
        [self handleDataWithCurrentValue:obj.currentValue andIndex:obj.currentIndex isDB:YES];
    }
    kDebug(@"--------数据库血糖数据处理完成-------------");
}

#pragma mark - 数据库

//将血糖数据保存到数据库
- (void)saveDataToDBWithCurrentValue:(int)currentValue andIndex:(int)currentIndex andBSValue:(float)BSValue
{
    BSDataObj *b = [[BSDataObj alloc]init];
    b.userID        = _defBSM.userID;
    b.deviceID      = _defBSM.deviceID;
    b.sensorID      = _defBSM.sensorID;
    b.currentIndex  = currentIndex;
    b.currentValue  = currentValue;
    b.referenceValue= _referenceValue;
    b.BSValue       = BSValue;
    b.isUpload      = NO;
    [[DBManage sharedManager] insertData:b andTable:kBloodSugarTable];
}


//从数据库获取某一段电流序号数据
- (NSArray *)getBSDataArrFromDBWithStartIndex:(NSInteger)startIndex toIndex:(NSInteger)toIndex
{
    NSString *conditionStr =
    [NSString stringWithFormat:@"%@ >= '%d' and %@ <= '%d' and %@",kCurrentIndex,startIndex,kCurrentIndex,toIndex,kQueryDBMust];
    
    NSArray *array = [[DBManage sharedManager] queryDataFromTable:kBloodSugarTable andConditions:conditionStr];
    
    return array;
}
//从数据库获取全部数据
- (NSArray *)getAllCurrentDataFromDB
{
    
    NSArray *array = [[DBManage sharedManager] queryDataFromTable:kBloodSugarTable andConditions:kQueryDBMust];
    
    return array;
}

#pragma mark - 蓝牙数据处理辅助函数



// 计算得出校验码
- (Byte)getVerifyFromData:(Byte *)temp andLength:(NSInteger)length
{
    Byte k = 0x0;
    for (int i = 0; i < length; i++) {
        k = k ^ temp[i];
    }
    return k;
}

//校验数据数据手否正确
- (BOOL)verifyData:(Byte *)temp andLength:(NSInteger)length
{    
    if ([self getVerifyFromData:temp andLength:length -1] == temp[length -1]) {
        return YES;
    }
    return NO;
}


//获取设备日志日期
- (NSDate *)getLogDateFromData:(Byte *)byte
{
    Byte bit3 = byte[7];
    Byte bit2 = byte[6];
    Byte bit1 = byte[5];
    Byte bit0 = byte[4];
    long timeInterval = (bit3<<24) + (bit2<<16) + (bit1<<8) + (bit0);
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeInterval];
    return date;
}

//显示设备警报
- (void)showDeviceAlertWithType:(Byte)alertType
{
    NSString *alertMessage;
    switch (alertType) {
        case 0x01:
            alertMessage = @"血糖电流过小";
            break;
        case 0x02:
            alertMessage = @"血糖电流过大";
            break;
        case 0x03:
            alertMessage = @"发射器电量低";
            break;
        case 0x04:
            alertMessage = @"传感器已到期限";
            break;
        case 0x05:
            alertMessage = @"日志存储区已满";
            break;
        default:
            alertMessage = @"";
            break;
    }
    kDebug(@"警告信息:%@",alertMessage);
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"警报" message:alertMessage delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alertView show];
}

- (void)postLocalNotificationWithAlertType:(Byte)alertType
{
    NSString *alertMessage;
    switch (alertType) {
        case 0x01:
            alertMessage = @"血糖电流过小";
            break;
        case 0x02:
            alertMessage = @"血糖电流过大";
            break;
        case 0x03:
            alertMessage = @"发射器电量低";
            break;
        case 0x04:
            alertMessage = @"传感器已到期限";
            break;
        default:
            alertMessage = @"";
            break;
    }
    kDebug(@"警告信息: %@",alertMessage);
    UILocalNotification *newNotification = [[UILocalNotification alloc] init];
    if (newNotification) {
        //时区
        newNotification.timeZone = [NSTimeZone defaultTimeZone];
        //推送事件---10秒后
        newNotification.fireDate = [[NSDate date] dateByAddingTimeInterval:0];
        //推送内容
        newNotification.alertBody = alertMessage;
        //应用右上角红色图标数字
        newNotification.applicationIconBadgeNumber = 1;
        //1:格式一定要支持播放，常用的格式caf
        //2:音频播放时间不能大于30秒
        //3:在Resource里要找到音频文件，倒入时最好能点项目名称右键add导入
        //        newNotification.soundName = @"jingBao2.caf";
        //设置按钮
        //        newNotification.alertAction = @"关闭";
        //判断重复与否
        //        newNotification.repeatInterval = NSWeekCalendarUnit;
        //存入的字典，用于传入数据，区分多个通知
        //        NSMutableDictionary *dicUserInfo = [[NSMutableDictionary alloc] init];
        //        [dicUserInfo setValue:[NSString stringFromDate:[NSDate date]] forKey:@"clockID"];
        //        float floatHeng = userLocation.location.coordinate.latitude;
        //        float floatShu = userLocation.location.coordinate.longitude;
        //        [dicUserInfo setValue:[NSString stringWithFormat:@"%f",strX] forKey:@"heng"];
        //        [dicUserInfo setValue:[NSString stringWithFormat:@"%f",strY] forKey:@"shu"];
        //        newNotification.userInfo = [NSDictionary dictionaryWithObject:dicUserInfo forKey:@"dictionary"];
        //        [[UIApplication sharedApplication] scheduleLocalNotification:newNotification];
        [[UIApplication sharedApplication] presentLocalNotificationNow:newNotification];
    }
}

//获取基本测试当天还有几个
-(NSInteger)getOfsetIndexFromStartMeasureDate
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit |
    NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    NSDateComponents *comps  = [calendar components:unitFlags fromDate:_defBSM.startMeasureDate];
    int hour = [comps hour];
    int min = [comps minute];
    int sec = [comps second];
    NSTimeInterval timeInterval  = (hour*60*60 + (min*60)+sec);//基本测试当天还有多少s
    NSInteger ofsetIndex = timeInterval/(60*3);
    return  ofsetIndex;
}



//倒计时
- (void)showCountDownTimeWithTimer:(NSTimer *)timer
{
    kDebug(@"倒计时 : %@,min = %d",[NSString stringFromDate:[NSDate date]],(int)_countDownTime);
    if (_countDownTime > 0) {
        NSNumber *style = (NSNumber *)timer.userInfo;
        _mainV.currentV.bspro.style = [style intValue] ;
        _mainV.currentV.bspro.z = _countDownTime;
        _countDownTime --;
    }else{
        if (_countDownTimer) {
            [_countDownTimer invalidate];
            _countDownTimer = nil;
        }
    }
}

//输入参比值    //注意，高低位交换
- (void)enterReferenceWithValue:(int)value shouldSaveReferenceValue:(BOOL)shouldSave
{
    int rslt = BGC_InputReference(value, 0);
    if (rslt == BGC_OK) {
        _referenceValue = value;
        if (shouldSave) {
            
            NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
            
            //参比值和改变参比值开始的数据序列号
            NSArray *arr = [def objectForKey:kReferenceArray ];
            NSMutableArray *refArray = [NSMutableArray array];
            if (arr) {
                refArray = [arr mutableCopy];//NSArray 转 NSMutableArray
                arr = [refArray copy];//NSMutableArray 转 NSArray
            }
            
            int last = [def integerForKey:kLastHandleIndex];
            if (last > 0 ) {
                NSDictionary *dic = [NSDictionary dictionaryWithObjects:@[[NSNumber numberWithInteger:_referenceValue],[NSNumber numberWithInt:last]] forKeys:@[kReferenceKey ,kReferenceIndex ]];
                
                kDebug(@"输入参比值: %d, Index = %d",value,last);
                [refArray addObject:dic];
                [def setObject:refArray forKey:kReferenceArray];
                [def synchronize];
                
                
                float bsvalue = [self handleDataWithCurrentValue:[def integerForKey:kLastHandleValue] andIndex:last isDB:NO];//重新计算输入参比值，最后一个血糖数据的值
                
                _countDownTime = 0;
                if (_countDownTimer) {
                    [_countDownTimer invalidate];
                    _countDownTimer = nil;
                }
                _mainV.currentV.bspro.style = ProgressBarStyleBlood;
                _mainV.currentV.bspro.z = bsvalue;
                
                [_mainV.currentV.canbi setTitle:[NSString stringWithFormat:kLocal(@"canbi"),refArray.count] forState:UIControlStateNormal];
            }
        }
    }
    else {
        if (rslt == BGC_K_TOOLOW) {
            kDebug(@"BGC K too low");
            if (_referenceValue != 0 ) {
                [self enterReferenceValueWithCancelOptions:YES descriptionText:@"参比血糖值太低"];
            } else {
                [self enterReferenceValueWithCancelOptions:NO descriptionText:@"参比血糖值太低"];
            }
        }
        else if (rslt == BGC_K_TOOHIGH) {
            kDebug(@"BGC K too low");
            if (_referenceValue != 0 ) {
                [self enterReferenceValueWithCancelOptions:YES descriptionText:@"参比血糖值太高"];
            } else {
                [self enterReferenceValueWithCancelOptions:NO descriptionText:@"参比血糖值太高"];
            }
        }
    }
}

- (void)enterReferenceValueWithCancelOptions:(BOOL)canCancel descriptionText:(NSString *)description
{
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    int last = [def integerForKey:kLastHandleIndex];
    if(!last)
        return;
    
    if (BGC_PermitRef()) {
        if (_inputReferenceAlert) {//如果是必须输入参比的，不弹出其他输入框，直接返回，不再弹出其他输入参比的框框
//            [_inputReferenceAlert dismissWithClickedButtonIndex:0 animated:NO];
//            _inputReferenceAlert = nil;
            return;
        }
        if (canCancel) {
            if (description != nil && ![description isEqualToString:@""]) {
                _inputReferenceAlert = [[UIAlertView alloc] initWithTitle:nil message:[NSString stringWithFormat:@"%@\n请输入参比血糖值（单位mmol/L）",description] delegate:self cancelButtonTitle:@"取消"  otherButtonTitles:@"确定", nil];
            }
            else {
                self.inputReferenceAlert = [[UIAlertView alloc] initWithTitle:nil message:@"请输入参比血糖值（单位mmol/L）" delegate:self cancelButtonTitle:@"取消"  otherButtonTitles:@"确定", nil];
            }
            _inputReferenceAlert.tag = 3003;//要判断确定才能输入参比值
        }
        else {
            _inputReferenceAlert = [[UIAlertView alloc] initWithTitle:nil message:@"请输入参比血糖值（单位mmol/L）" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            _inputReferenceAlert.tag = 3004;//不需要判断确定就能输入参比值
        }
        self.inputReferenceAlert.alertViewStyle = UIAlertViewStylePlainTextInput;
        UITextField *tf=[_inputReferenceAlert textFieldAtIndex:0];
        [tf setKeyboardType:UIKeyboardTypeDecimalPad];
        [self.inputReferenceAlert show];
        
        //提醒输入参比值
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
        AudioServicesPlaySystemSound(1007);
        
        if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
            UILocalNotification *noti = [[UILocalNotification alloc]init];
            noti.alertBody = @"请输入参比血糖值";
            noti.soundName = UILocalNotificationDefaultSoundName;
            [[UIApplication sharedApplication] presentLocalNotificationNow:noti];
        }
        
    }
    else {//无法输入参比值
        UIAlertView *alv = [[UIAlertView alloc] initWithTitle:@"提示" message:@"暂时无法输入参比" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alv show];
    }
}



#pragma mark - 提示代理函数 UIAlertViewDelegate


//将要显示警告框，修改textfield的键盘类型和placeholder
- (void)willPresentAlertView:(UIAlertView *)alertView
{
    if (alertView.tag == 3001) {
        UITextField *textField = [alertView textFieldAtIndex:0];
        textField.keyboardType = UIKeyboardTypeNumberPad;
        textField.placeholder = kLocal(@"4位数字");
        textField.secureTextEntry = YES;
    }
}

//点击警告框
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 3001) {
        
        if(buttonIndex == 0)
        {
            //不绑定则断开连接
            [_manage cancelPeripheralConnection:_peri];
            return;
        }
        UITextField *textField = [alertView textFieldAtIndex:0];
        NSString *str = textField.text;
        if (str.length != 4) {//如果警告框密码不是四位，警告提示
            UIAlertView *alv = [[UIAlertView alloc] initWithTitle:nil
                                                          message:kLocal(@"密码错误,请重新输入!")
                                                         delegate:self
                                                cancelButtonTitle:@"取消"
                                                otherButtonTitles:kLocal(@"OK"), nil];
            alv.alertViewStyle = UIAlertViewStylePlainTextInput;
            alv.tag = 3001;
            [alv show];
        }  else {
            
            _devicePassword = str;
            [self bindDevice];//用密码绑定设备
        }
    }
    else if (alertView.tag == 3003 ) {//要判断确定才能输入参比值
        _inputReferenceAlert = nil;
        if (buttonIndex == 1) {
            UITextField *textField = [alertView textFieldAtIndex:0];
            NSString *str = textField.text;
            if (str && str.length > 0 && [str floatValue] >= 2.0f && [str floatValue] <= 15.0f) {
                [self enterReferenceWithValue:([str floatValue])*10 shouldSaveReferenceValue:YES];
            }
            else {
                [self enterReferenceValueWithCancelOptions:YES descriptionText:@"输入的参比值错误，请重新输入"];
            }
        }else{
            [_mainV.currentV.canbi setEnabled:YES];
        }
    }
    else if (alertView.tag == 3004) {//不需要判断确定就能输入参比值
        _inputReferenceAlert = nil;
        UITextField *textField = [alertView textFieldAtIndex:0];
        NSString *str = textField.text;
        if (str && str.length > 0 && [str floatValue] >= 2.0f && [str floatValue] <= 15.0f) {
            [self enterReferenceWithValue:([str floatValue])*10 shouldSaveReferenceValue:YES];
            
        }
        else {
            [self enterReferenceValueWithCancelOptions:NO descriptionText:@"输入的参比值错误，请重新输入"];
        }
    }
    else if (alertView.tag == 5000) {//停止检测
        if (buttonIndex == 1) {
            [self disConnectDevice];
        }
    }
}


@end
